export class Circle {
  public x;
  public y;
  public r;
  public mx; // x轴的移动速度
  public my; // y轴的移动速度

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.r = 2;
    this.mx = Math.random();
    this.my = Math.random();
  }

  drawCircle(ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 360);
    ctx.closePath();
    ctx.fillStyle = 'rgba(21,21,30,0.65)';
    ctx.fill();
  }

  drawLine(ctx, circle) {
    const dx = this.x - circle.x;
    const dy = this.y - circle.y;
    const d = Math.sqrt(dx * dx + dy * dy);
    if (d < 100) {
      ctx.beginPath();
      ctx.moveTo(this.x, this.y);
      ctx.lineTo(circle.x, circle.y);
      ctx.strokeStyle = 'rgba(25,2,2,0.45)';
      ctx.stroke();
    }
  }

  move(w, h) {
    this.mx = (this.x < w && this.x > 0) ? this.mx : (-this.mx);
    this.my = (this.y < h && this.y > 0) ? this.my : (-this.my);
    this.x += this.mx / 2;
    this.y += this.my / 2;
  }
}

export class Main {
  private canvas;
  private ctx;
  public circles;
  public deltaTime;

  constructor() {
    this.canvas = document.querySelector('canvas');
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.ctx = this.canvas.getContext('2d');
    this.circles = [];
    this.deltaTime = 0;
  }

  draw() {
    this.deltaTime = ++this.deltaTime % 3;
    const w = this.canvas.width;
    const h = this.canvas.height;
// tslint:disable-next-line: triple-equals
    if (this.deltaTime == 2) {
      this.ctx.clearRect(0, 0, w, h);
      for (let i = 0; i < this.circles.length; i++) {
        this.circles[i].move(w, h);
        this.circles[i].drawCircle(this.ctx);
        for (let j = i + 1; j < this.circles.length; j++) {
          this.circles[i].drawLine(this.ctx, this.circles[j]);
        }
      }
    }
    requestAnimationFrame(this.draw.bind(this));
  }

  main() {
    const num = 100;
    const w = this.canvas.width;
    const h = this.canvas.height;
    for (let i = 0; i < num; i++) {
      this.circles.push(new Circle(Math.random() * w, Math.random() * h));
    }
    this.draw();
  }
}
